package hu.issue.ejb;

import hu.issue.entity.Milestone;
import hu.issue.entity.Task;
import hu.issue.exceptions.MilestoneNotFoundException;
import hu.issue.exceptions.TaskNotFoundException;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class MilestoneServiceBean implements MilestoneService {
	@PersistenceContext
	private EntityManager manager;
	@EJB
	private TaskService taskService;

	@Override
	public void assignTaskToMilestone(final int milestoneId, final int taskId) throws MilestoneNotFoundException, TaskNotFoundException {
		final Task task = this.taskService.findTaskById(taskId);
		final Milestone milestone = findMilestoneById(milestoneId);
		milestone.addTask(task);
	}

	@Override
	public Milestone findMilestoneById(final int id) throws MilestoneNotFoundException {
		final Milestone milestone = this.manager.find(Milestone.class, id);
		if (milestone == null) {
			throw new MilestoneNotFoundException();
		}
		return milestone;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Milestone> getMilestones() {
		final Query query = this.manager.createQuery("select m from Milestone m");
		return query.getResultList();
	}

}
